package classes
{
	import classes.event.SessionEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.net.ObjectEncoding;
	
	public class Red5Facade extends EventDispatcher {
		private static var instance:Red5Facade = new Red5Facade();
		
		private var m_nc:NetConnection;
		private var m_ns:NetStream;
    private var m_ClientCallback:Object = {};
    
    private var generalService:GeneralServiceInteracter;
    private var objectService:ObjectServiceInteracter;
    private var consoleService:ConsoleServiceInteracter;
        
		public function Red5Facade() {
			m_ClientCallback.onMetaData = function onMeta():void {
				trace("onMeta");
			};
	    m_nc = new NetConnection();
	    m_nc.objectEncoding = ObjectEncoding.AMF3;
	    m_nc.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
	    generalService = new GeneralServiceInteracter(m_nc);
	    objectService = new ObjectServiceInteracter(m_nc);
	    consoleService = new ConsoleServiceInteracter(m_nc);
	    m_nc.client = this;
		}
		
		public function grantSession(user:String, password:String, server:String = "localhost"):void {
			//m_nc.connect("rtmp://" + URLUtil.getServerName(Application.application.loaderInfo.url) + "/core", user, password);
			m_nc.connect("rtmp://" + server + "/core", user, password);
		}
		
		public function discardSession():void {
			m_nc.close();
			dispatchEvent(new SessionEvent(SessionEvent.UNSET));
		}
		
		public function get general():GeneralServiceInteracter {
			return generalService;
		}
		
		public function get object():ObjectServiceInteracter {
			return objectService;
		}
		
		public function get console():ConsoleServiceInteracter {
			return consoleService;
		}
		
		public static function getInstance():Red5Facade {
			return instance;
		}
		
    private function netStatus(event:NetStatusEvent):void {
      trace("NetStatus: " + event.info.code);
      if(event.info.code == "NetConnection.Connect.Rejected") {
        dispatchEvent(new SessionEvent(SessionEvent.ERROR, event.info.application));
      } else if(event.info.code == "NetConnection.Connect.Success") {
      	dispatchEvent(new SessionEvent(SessionEvent.SET));
      }
    }
    
    public function getStream():NetStream {
    	return m_ns;
    }
	}
}